package com.weblog.user.controller;

import com.weblog.model.user.Admin;
import com.weblog.model.user.Role;
import com.weblog.user.entity.AdminInfoDTO;
import com.weblog.user.entity.AdminVo;
import com.weblog.user.service.AdminService;
import entity.PageResult;
import entity.Result;
import entity.ResultMessage;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;


    @Autowired
     private JwtUtil<String> jwtUtil;




    /**
     * 登录
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin){
        AdminInfoDTO dto= adminService.login(admin);
        if(dto==null){
           return  new Result(false, StatusCode.LOGINERROR, ResultMessage.LOGIN_ERROR);

       }

        Admin login_admin=dto.getAdmin();
        //登录用户的角色列表
        List<Role>roles_list= dto.getRoles();
        List<String>roles=new ArrayList<>();
        for(Role role : roles_list){
            roles.add(role.getRname());
        }
        //生成token
        String token = jwtUtil.createJWT(login_admin.getId(), login_admin.getUsername(), roles);

        //存储返回数据
        int mapSize=(int)((3 / 0.75) +1);
        Map<String,Object> data =new HashMap<>(mapSize);

        AdminVo adminVo=new AdminVo();
        adminVo.setRole(roles);
        adminVo.setToken(token);
        adminVo.setUsername(login_admin.getUsername());
       // data.put("avatar",login_user.getAvatar());
        return  new Result(true, StatusCode.OK, ResultMessage.LOGIN_SUCCESS,adminVo);

    }

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result PageBySearch(@RequestBody Map<String, Object> searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Admin> pageList = adminService.PageBySearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<Admin>(pageList.getTotalElements(), pageList.getContent()));
    }


    /**
     * 拉黑
     *
     * @param id
     */
    @PutMapping(value = "/black/{id}")
    public Result blackUser(@PathVariable("id") String id) {
        int flag = adminService.blackAdmin(id);
        if (flag == 2) {
            return new Result(false, StatusCode.ACCESSERROR, "权限不足");
        } else if (flag == 1) {
            return new Result(true, StatusCode.OK, "拉黑成功");
        }

        return new Result(false, StatusCode.ERROR, "拉黑失败");

    }

    /**
     * 根据ID查询管理员信息
     *
     * @param id ID
     * @return
     */
    @GetMapping(value = "/{id}")
    public Result findById(@PathVariable String id) {
        Admin admin = adminService.findById(id);
        if (admin == null) {
            return new Result(false, StatusCode.ERROR, "管理员不存在");
        }
        return new Result(true, StatusCode.OK, "查询成功", admin);
    }

    /**
     * 增加管理员
     *
     * @param admin
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Admin admin) {
        int flag = adminService.add(admin);
        if (flag == 1) {
            return new Result(true, StatusCode.OK, ResultMessage.SAVE_SUCCESS);
        } else if (flag == 3) {
            return new Result(false, StatusCode.REPERROR, ResultMessage.USER_EXISTED);
        }
        return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);

    }

    /**
     * 修改
     *
     * @param admin
     */
    @PutMapping(value = "/{id}")
    public Result update(@RequestBody Admin admin, @PathVariable String id) {
        admin.setId(id);
        int flag = adminService.update(admin);
        if (flag == 1) {
            return new Result(true, StatusCode.OK, ResultMessage.UPDATE_SUCCESS);
        } else if (flag == 3) {
            return new Result(false, StatusCode.REPERROR, ResultMessage.USER_EXISTED);
        }else if(flag==4){
            return new Result(false, StatusCode.ERROR, "无权修改其状态！");
        }
        return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);
    }

    /**
     * 给管理员分配角色
     *
     * @param id
     * @param rid
     * @return
     */
    @PostMapping("/role/{id}/{rid}")
    public Result addRoleToAdmin(@PathVariable String id, @PathVariable String rid) {
        int flag = adminService.addRoleToAdmin(id, rid);
        if (flag == 1) {
            return new Result(true, StatusCode.OK, ResultMessage.SAVE_SUCCESS);
        } else if (flag == 2) {
            //权限不足
            return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);
        } else if (flag == 4) {
            return new Result(false, StatusCode.NOT_ALLOWED, "不可分配superAdmin");
        }
        //重复分配
        return new Result(false, StatusCode.NOT_ALLOWED, ResultMessage.DATA_REPETED);
    }

    /**
     * 根据管理员id查询角色列表
     *
     * @param id
     * @return
     */
    @GetMapping("/role/{id}")
    public Result queryRoleListByUserid(@PathVariable("id") String id) {
        List<Role> roleList = adminService.queryRoleListByAdminid(id);
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, roleList);
    }

    /**
     * 根据管理员id删除角色关系
     *
     * @param id
     * @param rid
     * @return
     */
    @DeleteMapping("/role/{id}/{rid}")
    public Result deleteRoleOfAdmin(@PathVariable("id") String id, @PathVariable("rid") String rid) {
        int flag = adminService.deleteRoleOfAdmin(id, rid);
        if (flag == 0) {
            return new Result(false, StatusCode.NOT_ALLOWED, "基础角色不可删除");
        } else if (flag == 2) {
            return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);
        }
        return new Result(true, StatusCode.OK, ResultMessage.DELETE_SUCCESS);

    }
}
